var fs=require('fs');
var events=require('events');
var util=require('util');

function Watcher(watchDir,copyDir){
    this.watchDir=watchDir;
    this.copyDir=copyDir;
}
util.inherits(Watcher,events.EventEmitter);

Watcher.prototype.start= function () {
    var that=this;
    fs.readdir(that.watchDir, function (err, files) {
        if(err)throw err;
        for(var i in files){
            that.watch(files[i]);
        }
    });
}

Watcher.prototype.watch= function (file) {
    console.log('watch file:',file);
    var that=this;
    fs.watchFile(that.watchDir+'/'+file, function (curr, prev) {
        console.log(file,'changed !!');
        that.emit('process:',file);
    });
}


var watcher=new Watcher('./watch','./done');
watcher.start();
watcher.on('process', function (file) {
    console.log('process:',file);

    var that=this;
    fs.readFile(that.watchDir+'/'+file, function (err, data) {
        if(err)throw '复制 时读取文件失败！';
        console.log('data:',data);
        fs.open(that.copyDir+'/'+file,'w',function (err,fd) {
            if(err)throw '打开待写入文件失败！';
            fs.write(fd,data,0,data.length,0, function (err) {
                if(err)throw '写入文件失败！';
                console.info('写入文件成功！');
            });
        });
    });
});
